package com.example.springboottest.example.atomic;

import com.example.springboottest.util.Print;
import com.example.springboottest.util.ThreadUtil;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest {
    static final int THREAD_COUNT = 5;

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
        //定义一个整数原子类实例，赋值到变量 i
        AtomicInteger atomicInteger = new AtomicInteger(0);
        for (int i = 0; i < THREAD_COUNT; i++) {
            // 创建5个线程，模拟多线程环境
            ThreadUtil.getMixedTargetThreadPool().submit(() -> {
                for (int j = 0; j < 1000; j++) {
                    atomicInteger.getAndIncrement();
                }
                latch.countDown();
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Print.tco("累加之和：" + atomicInteger.get());
    }
}
